import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import store from "../store/index";

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/views/Home.vue"),
    meta: {
      title: "芊图社",
    },
  },
  {
    path: "/share",
    name: "Share",
    component: () => import("@/views/Share.vue"),
    meta: {
      requiresAuth: true,
      title: "发布",
    },
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue"),
    meta: {
      title: "登录",
    },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/Register.vue"),
    meta: {
      title: "注册",
    },
  },
  {
    path: "/profile",
    name: "Profile",
    component: () => import("@/views/Profile.vue"),
    meta: {
      requiresAuth: true,
      title: "个人中心",
    },
    children: [
      {
        path: "",
        name: "TimeLine",
        component: () => import("@/components/TimeLine.vue"),
        meta: {
          title: "我的作品",
        },
      },
      {
        path: "collect",
        name: "Collect",
        component: () => import("@/components/Collect.vue"),
        meta: {
          title: "我的消息",
        },
      },
    ],
  },
  {
    path: "/details/:id",
    name: "Details",
    component: () => import("@/views/Details.vue"),
    meta: {
      title: "详情",
    },
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  //获取store里面的token
  const token = store.state.token;
  //判断要去的路由有没有requiresAuth
  if (to.meta.requiresAuth) {
    if (token) {
      next();
    } else {
      next({
        path: "/login",
        // 将刚刚要去的路由path作为参数，方便登录成功后直接跳转到该路由
        query: { redirect: to.fullPath },
      });
    }
  } else {
    next();
  }
  // 改变标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }
});

export default router;
